import logging

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect, redirect_to

from google.appengine.ext import db
from monkeytest.model import TestSuite, TestCase

from monkeytest.lib.base import BaseController, render, h

log = logging.getLogger(__name__)

class TestsuiteController(BaseController):
    def show(self, name=None):
        testsuites = TestSuite.gql("WHERE name = :1", name)
        c.name = name
        
        for testsuite in testsuites:
            c.testcases = TestCase.gql("WHERE testsuite = :1", testsuite.key())
            c.key = str(testsuite.key())
            c.project = testsuite.project
            
        return render('testsuite/show.html')
    
    def save(self):
        if request.params.has_key('key'):
            testsuite = db.get(db.Key(request.params['key']))
        else:
            testsuite = TestSuite()
            testsuites = TestSuite.gql("WHERE name = :1", request.params['name'])
            if testsuites.count() > 0:
                h.flash("Name exists")
                redirect_to('new_testsuite')
        
        testsuite.name = request.params['name']
        testsuite.project = request.params['project']
        
        db.put(testsuite)
        redirect_to("show_testsuite", name=testsuite.name)
        
    def list(self):
        c.testsuites = {}
        testsuites = TestSuite.all()
        for testsuite in testsuites:
            if not c.testsuites.has_key(testsuite.project):
                c.testsuites[testsuite.project] = []
            c.testsuites[testsuite.project].append(testsuite)
            
        return render('testsuite/list.html')
    
    